<template>
	<view class="garden-page">
		<view class="header">
            <image class="gd-icon" @click="goHome" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd.png" mode=""></image>
			<text class="title">一尺花园·宠物友好课程</text>
		</view>
		<!-- 轮播图 -->
		<view class="banner-container" v-if="!isLoading && activityInfo.img_list && activityInfo.img_list.length > 0">
			<uni-swiper-dot :info="activityInfo.img_list" :current="current" mode="dot" :dots-styles="dotsStyles">
				<swiper class="banner-swiper" :autoplay="true" :interval="3000" :duration="500" @change="change">
					<swiper-item v-for="(imageUrl, index) in activityInfo.img_list" :key="index">
						<image class="banner-image" :src="imageUrl" mode="aspectFill" @error="onImageError"></image>
					</swiper-item>
				</swiper>
			</uni-swiper-dot>
		</view>
		<!-- 轮播图加载中 -->
		<view class="banner-loading" v-else-if="isLoading">
			<text class="loading-text">轮播图加载中...</text>
		</view>
		<!-- 无轮播图数据 -->
		<view class="banner-empty" v-else>
			<text class="empty-text">暂无轮播图</text>
		</view>

        <!-- 活动简介卡片 -->
        <view class="activity-card" v-if="!activityLoading && activityInfo" >
            <!-- 这里是卡片右上角的标签有三种状态会切换，活动结束，报名中，活动预约中 -->
             <view class="activity-tag" :class="getStatusInfo().class">
                <text class="tag-text">{{ getStatusInfo().text }}</text>
             </view>
             <!-- 这里是卡片的标题 -->
             <text class="activity-title">
                {{ activityInfo?.title || '活动标题加载中...' }}
             </text>
             <!-- 店名 -->
             <view class="activity-store">
                <!-- 门店logo -->
                <image class="store-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-md.png" mode=""></image>
                {{ activityInfo?.merchant_name || '店名加载中...' }}
             </view>
             <!-- 活动时间 -->
             <view class="activity-time">
                <image class="time-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-sj.png" mode=""></image>
                {{ activityInfo?.show_time || '时间待定' }}
             </view>
             <!-- 活动地点 -->
             <view class="activity-location">
                <image class="location-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-dz.png" mode=""></image>
                {{ activityInfo?.address || '地点待定' }}
                <image class="navigatio-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-dh.png" mode="" @click="openLocation"></image>
             </view>
             <!-- 前三名头像，多少人已报名，仅剩于多少人 -->
             <view class="activity-top-three">
                <view class="top-three-avatars">
                    <image 
                                v-for="(user, index) in (activityInfo?.users || [])" 
                                :key="index" 
                                class="top-three-avatar" 
                                :src="user.avatar || '/static/images/logo.png'" 
                                mode="aspectFill"
                                @error="onImageError"
                            ></image>
                    <text class="top-three-text">
                        {{ activityInfo?.total_num || 0 }}人已{{ (activityInfo?.status === 1) ? '预约' : (activityInfo?.status === 2) ? '报名' : '参与' }}
                    </text>
                </view>
                <!-- 可预约状态：显示开始报名时间 -->
                <text class="top-three-remaining status-bookable" v-if="activityInfo?.status === 2">
                    {{ activityInfo?.show_enroll_time || '4月23日 10:00' }}开始报名
                </text>
                <!-- 报名中状态：显示剩余名额 -->
                <template v-else-if="activityInfo?.status === 1 || activityInfo?.status === 3">
                    <text class="top-three-remaining status-active" v-if="(activityInfo?.remain_num || 0) > 0">
                        仅剩 {{ activityInfo?.remain_num || 0 }} 个名额
                    </text>
                    <text class="top-three-remaining status-active" v-else>
                        名额已满
                    </text>
                </template>
                <!-- 已结束状态：不显示任何内容 -->
             </view>
        </view>
        <!-- 活动加载中 -->
        <view class="activity-card activity-loading" v-else-if="activityLoading">
            <text class="loading-text">活动信息加载中...</text>
        </view>
        <!-- 无活动数据 -->
        <view class="activity-card activity-empty" v-else>
            <text class="empty-text">暂无活动信息</text>
        </view>

        <!-- 活动详情 -->
        <view class="activity-detail" v-if="activityInfo">
            <!-- 活动标题 -->
            <text class="title">活动详情</text>
			<view v-if="activityInfo.img_list.length>0">
			   <image class="activity-detail-image" :src="imageUrl" v-for="(imageUrl, index) in activityInfo.img_list" :key="index" mode="aspectFill" @error="onImageError"></image>
			</view>
        </view>

        <!-- 购买须知 -->
        <view class="activity-notice" v-if="activityInfo && activityInfo?.desc">
            <text class="title">购买须知</text>
            <text class="detail-text">
                {{ activityInfo?.desc || '' }}
            </text>
        </view>

        <!-- 底部操作栏 -->
        <view class="bottom-bar">
            <!-- 门店icon和名称 -->
            <view class="bottom-bar-store" @click="goToMerchantDetail">
                <image class="store-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-md-db.png" mode=""></image>
                <text class="store-name">门店</text>
            </view>
            <!-- 发笔记icon和名称 -->
            <view class="bottom-bar-note" @click="openApp">
                <image class="note-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-fbj-db.png" mode=""></image>
                <text class="note-name">发笔记</text>
            </view>
            <!-- 报名按钮 -->
            <view class="bottom-bar-button" 
                  :style="{ backgroundColor: getButtonInfo().backgroundColor || '#FFDA61' }"
                  @click="handleButtonClick">
                <text class="button-text">{{ getButtonInfo().text }}</text>
            </view>
        </view>
		
		<!-- 报名抽屉 -->
		<uni-popup ref="registrationDrawer" type="bottom" background-color="#ffffff" :border-radius="'24rpx 24rpx 0rpx 0rpx'">
			<view class="registration-drawer">
			<!-- 右上角的关闭按钮 -->
			<view class="close-btn" @click="closeDrawer">
				<image src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-gb-bm.png" mode=""></image>
			</view>
			
			<!-- 报名表单内容 - 只在未成功报名时显示 -->
			<view v-if="!registrationSuccess">
				<!-- 标题 -->
				<text class="title">报名账号</text>
				<!-- 头像和用户名 -->
				<view class="user-info">
					<image class="user-avatar" :src="userInfo?.avatar || '/static/icons/gd-avatar.svg'" mode="aspectFill" @error="onImageError"></image>
					<text class="user-name">{{ userInfo?.name || '未命名用户' }}</text>
				</view>
				<!-- 活动卡片背景是一个图片，上面有标题，报名截止日期，剩余N张限购1张，右上角有一个选中的icon和标题同行 -->
				<view class="activity-card">
					<image class="activity-card-bg" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-bm-bg.png" mode="scaleToFill" @error="onImageError"></image>
					<view class="activity-card-header">
						<text class="activity-card-title">{{ activityInfo?.title || '活动标题' }}</text>
						<image class="activity-card-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-gx-bm.png" mode="aspectFill" @error="onImageError"></image>
					</view>
					<text class="activity-card-end">报名截止时间：{{ formatTimeForDisplay(activityInfo?.time) }}</text>
					<text class="activity-card-remain">仅剩 {{ activityInfo?.remainPeople || 0 }} 个名额 限购1张</text>
				</view>
				<!-- 确认报名按钮 -->
				<button @click="confirmRegistration">
					确认报名
				</button>
			</view>
			
			<!-- 报名成功后的内容 -->
			<view v-if="registrationSuccess" class="success-content">
				<image class="success-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-cg-bm.png" mode="aspectFill"></image>
				<text class="success-title">恭喜您，报名成功！</text>
				<text class="success-desc">您已经成功报名 {{ activityInfo?.title || 'XXXXXXXX' }} 活动，活动将于 {{ formatActivityDate(activityInfo?.time) }} 举行，请准时参加。\n届时到场后，请点击【现场签到】，结课后点击【结课打卡】，以获得活动集章。</text>
				<button class="share-btn" open-type="share">分享给好友</button>
				<button class="return-btn" @click="returnToPage">返回</button>
			</view>
		</view>
		</uni-popup>

		<!-- 签到弹窗 -->
		<uni-popup ref="checkinModal" type="center" background-color="transparent">
			<view class="checkin-modal">
				<!-- 关闭按钮 -->
				<view class="checkin-close-btn" @click="closeCheckinModal">
					<image src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-gb-bm.png" mode=""></image>
				</view>
				
				<!-- 签到成功状态 -->
				<view v-if="checkinStatus === 'success'" class="checkin-content">
					<text class="checkin-title">签到成功</text>
					<image class="checkin-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-cg-bm.png" mode="aspectFill"></image>
				</view>
				
				<!-- 预约成功状态 -->
				<view v-if="reservationStatus === 'success'" class="checkin-content">
					<text class="checkin-title">预约成功</text>
					<image class="checkin-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-cg-bm.png" mode="aspectFill"></image>
				</view>
				
				<!-- 签到失败状态（距离不够） -->
				<view v-if="checkinStatus === 'distance_fail'" class="checkin-content">
					<text class="checkin-title">签到失败</text>
					<image class="checkin-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-sb-bm.png" mode="aspectFill"></image>
					<text class="checkin-desc">{{ checkinErrorMessage || '当前距离较远，请靠近后再打卡' }}</text>
				</view>
				
				<!-- 预约失败状态 -->
				<view v-if="reservationStatus === 'fail'" class="checkin-content">
					<text class="checkin-title">预约失败</text>
					<image class="checkin-icon" src="https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/gd-sb-bm.png" mode="aspectFill"></image>
					<text class="checkin-desc">{{ reservationErrorMessage || '预约失败，请稍后再试' }}</text>
				</view>
				
				<!-- 时间不够状态 -->
				<view v-if="checkinStatus === 'time_fail'" class="checkin-content">
					<text class="checkin-title">当前时间不可签到</text>
					<text class="checkin-desc">请在活动开课时间内，进行位置签到</text>
				</view>
				
				<!-- 确定按钮（只在时间失败时显示） -->
				<button v-if="checkinStatus === 'time_fail'" class="checkin-confirm-btn" @click="closeCheckinModal">确定</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { navTo, getIndexShareObject } from '../../common/utils.js'
import { useUserStore } from '../../store/userStore.js'
import { mapState } from 'pinia'

export default {
	name: 'GardenIndex',
	computed: {
		...mapState(useUserStore, ['userInfo'])
	},
	data() {
		return {
			// 活动ID（持久化保存）
			activityId: null,
			// 轮播图数据
			bannerList: [],
			// 加载状态
			isLoading: false,
			current: 0,
			dotsStyles: {
				width: 10,
				height: 10,
				bottom: 30,
				backgroundColor: '#FFFFFF',
				selectedBackgroundColor: '#FFBF33',
				borderRadius: 0
			},
			// 活动详情数据
			activityInfo: {
				img_list:[]
			},
			// 活动加载状态
			activityLoading: false,
			// 用户状态数据
			userStatus: null,
			// 用户状态加载状态
			userStatusLoading: false,
			// 报名成功状态
			registrationSuccess: false,
			// 签到弹窗状态
			checkinStatus: null, // 'success', 'distance_fail', 'time_fail'
			// 签到错误信息
			checkinErrorMessage: '',
			// 预约弹窗状态
			reservationStatus: null, // 'success', 'fail'
			// 预约错误信息
			reservationErrorMessage: ''
		}
	},
	onLoad(options) {
		// 页面加载时执行
		const userStore = useUserStore()
		userStore.getUserInfo()
		// 获取页面参数中的activity_id并保存到data中
		const activityId = options?.activity_id;
		if (activityId) {
			this.activityId = activityId;
			this.getDetail();
		}
	},
	methods: {
		async getDetail() {
			const id = this.activityId
			const res = await this.$request.get('/api/activity/detail_v2',{id})
			if (res.code == 200) {
				this.bannerList = res.data.img_list;
				this.activityInfo = res.data;
			}else{
				uni.showToast({
					title: '获取信息失败',
					icon: 'none'
				});
			}
		},
		// 页面方法
		goHome() {
			uni.navigateTo({
				url: '/pages/garden/map'
			})
		},
		openApp() {
			const url = "https://m.ix5j.cn";;
			uni.navigateTo({
				url: '/pages/webview/index?url=' + url
			})
			return
		},
		
		// 跳转到商户详情页
		goToMerchantDetail() {
			if (!this.activityInfo || !this.activityInfo.merchant_id) {
				uni.showToast({
					title: '商户信息不存在',
					icon: 'none'
				});
				return;
			}
			
			uni.navigateTo({
				url: `/pages/merchant/detail?merchantId=${this.activityInfo.merchant_id}`
			});
		},
		
		change(e) {
			this.current = e.detail.current
		},
		
		
		// 图片加载失败处理
		onImageError(e) {
			// 轮播图加载失败处理
		},
		
		// 格式化时间显示
		formatTimeForDisplay(timeStr) {
			if (!timeStr) return '报名截止时间未指定';
			
			// 匹配格式：4月23日 周日 10:00～22:00
			const timePattern = /(\d+月\d+日).*?(\d{2}:\d{2})～(\d{2}:\d{2})/;
			const match = timeStr.match(timePattern);
			
			if (match) {
				const date = match[1]; // 4月23日
				const endTime = match[3]; // 22:00
				return `${date} ${endTime}`;
			}
			
			// 如果不匹配预期格式，返回原始字符串
			return timeStr;
		},
		getStatusInfo() {
			if (!this.activityInfo) {
				return {
					text: '报名中',
					class: 'status-active'
				};
			}
			switch (this.activityInfo?.status) {
				case 1:
					return {
						text: '可预约',
						class: 'status-bookable'
					};
                case 2:
					return {
						text: '报名中',
						class: 'status-active'
					};
                case 3:
					return {
						text: '可签到',
						class: 'status-active'
					};
				case 4:
					return {
						text: '已结束',
						class: 'status-ended'
					};

				default:
					return {
						text: '可预约',
						class: 'status-active'
					};
			}
		},
		
		// 获取按钮状态信息
		//活动状态 1-可预约 2-报名中 3-可签到 4-已结束
		//当前用户状态 1-未预约 2-已预约-未报名 3-已报名未签到  4-已签到
		getButtonInfo() {
			if (!this.activityInfo || this.userStatusLoading) {
				return {
					text: '加载中...',
					enabled: false,
					backgroundColor: '#F5F5F5'
				};
			}
			
			const activityStatus = this.activityInfo?.status;          //活动状态
			const enrollStatus   = this.activityInfo?.enroll_status;   //报名状态 0-未,1-已经
			const bookStatus     = this.activityInfo?.book_status;     //预约状态 0-未,1-已经
			const signInStatus   = this.activityInfo?.sign_in_status;  //签到状态 0-未,1-已经
			
			let textVal            = '';
			let backgroundColorVal = '#F5F5F5';
			let enabledVal         = false;
			
			// 活动状态：1 - 可预约
			if (activityStatus === 1) {
				textVal            = '不可预约';
				backgroundColorVal  = '#F5F5F5';
				enabledVal         = false;
				if (bookStatus ==0) {
					textVal            = '预约',
					enabledVal         = true,
					backgroundColorVal = '#FFDA61'
				}
				if (bookStatus ==1) {
					textVal            = '已预约',
					enabledVal         = false,
					backgroundColorVal = '#F5F5F5'
				}
				return {
					text: textVal,
					enabled: enabledVal,
					backgroundColor: backgroundColorVal
				};
			}
			
			// 活动状态：2 - 报名中
			if (activityStatus === 2) {
				textVal            = '不可报名';
				backgroundColorVal  = '#F5F5F5';
				enabledVal         = false;
				
				if (enrollStatus ==0) {
					textVal            = '报名',
					enabledVal         = true,
					backgroundColorVal = '#FFDA61'
				}
				
				if (enrollStatus ==1) {
					textVal            = '已报名',
					enabledVal         = false,
					backgroundColorVal = '#F5F5F5'
				}
				
				return {
					text: textVal,
					enabled: enabledVal,
					backgroundColor: backgroundColorVal
				};
				
			}
			
			// 活动状态：3 - 可签到
			if (activityStatus === 3) {
				if (enrollStatus ==1 && signInStatus == 0) {
					textVal            = '签到',
					enabledVal         = true,
					backgroundColorVal = '#FFDA61'
				}else if(enrollStatus ==1 && signInStatus == 1){
					textVal            = '已签到',
					enabledVal         = true,
					backgroundColorVal = '#F5F5F5'
				}else{
					textVal            = '不可签到';
					ackgroundColorVal  = '#F5F5F5';
					enabledVal         = false;
				}
				return {
					text: textVal,
					enabled: enabledVal,
					backgroundColor: backgroundColorVal
				};
			}
			
			// 活动已结束
			if (activityStatus === 4) {
				return {
					text: '已结束',
					enabled: false,
					backgroundColor: '#F5F5F5'
				};
			}
			// 默认情况
			return {
				text: '不可操作',
				enabled: false,
				backgroundColor: '#F5F5F5'
			};
		},
		
		// 处理按钮点击事件
		handleButtonClick() {
			const buttonInfo = this.getButtonInfo();
			
			// 如果按钮不可点击，直接返回，不执行任何操作
			if (!buttonInfo.enabled) {
				return;
			}
			
			// 检查用户是否已登录
			const userStore = useUserStore();
			if (userStore.userId <= 0) {
				uni.showModal({
					title: '欢迎来到See Wow小程序！', // 弹窗标题
					content: '在开始体验前，为确保您能顺畅查看已购套餐、完成线下核销等必要功能，我们需要您先授权登录，请放心，我们始终将您的隐私和使用体验放在首位；'+'\r\n\n'+ '🔒 严格保护隐私：您的个人信息仅用于小程序功能实现，不会向商家或其他第三方提供。\r\n\n 🛍️ 便捷管理：登录后可随时查询订单、核销权益，不错过任何宠物友好福利！\r\n\r\n 点击下方按钮快速授权，马上开启您和爱宠的专属旅程吧～ ✨', // 弹窗内容
					showCancel: true, // 是否显示取消按钮
					cancelText: '取消', // 取消按钮的文字，默认为"取消"
					cancelColor: '#000000', // 取消按钮的文字颜色
					confirmText: '确认授权', // 确认按钮的文字，默认为"确定"
					confirmColor: '#3CC51F', // 确认按钮的文字颜色
					success: function (res) {
						if (res.confirm) {
							// 用户点击了确定按钮
							uni.navigateTo({
								url: '/pages/login/login'
							})
							//console.log('用户点击了确定');
							// 在这里执行你的逻辑
						} else if (res.cancel) {
							// 用户点击了取消按钮
							//console.log('用户点击了取消');
						}
					}
				});
				return;
			}
			
			// 根据按钮文字执行不同的操作
			switch (buttonInfo.text) {
				case '报名':
					this.handleRegistration();
					break;
				case '预约':
					this.handleReservation();
					break;
				case '签到':
					this.handleCheckIn();
					break;
				default:
					// 未知的按钮操作
					break;
			}
		},
		
		// 处理报名
		handleRegistration() {
			const agreed = uni.getStorageSync('agreedToGardenTerms') || false;
			if (agreed) {
				this.$refs.registrationDrawer.open();
			} else {
				this.showAgreementModal();
			}
		},
		
		// 处理预约
		async handleReservation() {
			try {
				// 调用预约接口，使用和报名相同的接口，但状态为3（已预约）
				const res = await this.$request.post('/api/activity/behavior', {
					activity_id: this.activityInfo?.id,
					type: 1 
				});
				if (res.code === 200) {
					// 预约成功
					this.reservationStatus = 'success';
					this.$refs.checkinModal.open();
					this.getDetail();
				} else {
					// 预约失败
					this.reservationStatus = 'fail';
					this.reservationErrorMessage = '预约失败，请稍后再试';
					this.$refs.checkinModal.open();
				}
			} catch (error) {
				// 网络异常或其他错误
				this.reservationStatus = 'fail';
				this.reservationErrorMessage = '预约失败，请稍后再试';
				this.$refs.checkinModal.open();
			}
		},
		
		// 处理签到
		async handleCheckIn() {
			try {
				// 获取当前位置
				const location = await this.getCurrentLocation();
				if (!location) {
					this.checkinStatus = 'distance_fail';
					this.checkinErrorMessage = '获取位置失败，请检查定位权限';
					this.$refs.checkinModal.open();
					return;
				}
				
				const result = await this.$request.post('/api/activity/behavior', {
					activity_id: this.activityInfo?.id,
					type: 3,
					lng:location.longitude,
					lat:location.latitude,
				});
				
				// 根据接口返回结果显示相应弹窗
				if (result.code === 200) {
					this.checkinStatus = 'success';
				} else {
					// 根据错误码判断失败类型
					if (result.code === 4001) {
						// 距离不够
						this.checkinStatus = 'distance_fail';
						this.checkinErrorMessage = result.msg;
					} else if (result.code === 4002) {
						// 时间未到
						this.checkinStatus = 'time_fail';
					} else if (result.code === 5000) {
						// 其他报错
						this.checkinStatus = 'distance_fail';
						this.checkinErrorMessage = result.msg;
					} else {
						// 其他未知错误，默认显示距离失败
						this.checkinStatus = 'distance_fail';
						this.checkinErrorMessage = result.msg;
					}
				}
				
				// 显示弹窗
				this.$refs.checkinModal.open();
			} catch (error) {
				// 网络错误或其他异常，默认显示距离失败
				this.checkinStatus = 'distance_fail';
				this.checkinErrorMessage = '签到失败，请稍后再试';
				// 显示弹窗
				this.$refs.checkinModal.open();
			}
		},
		
		// 获取当前位置
		getCurrentLocation() {
			return new Promise((resolve, reject) => {
				uni.getLocation({
					type: 'gcj02', // 返回可以用于uni.openLocation的经纬度
					success: (res) => {
						resolve({
							latitude: res.latitude,
							longitude: res.longitude
						});
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						uni.showToast({
							title: '获取位置失败，请检查定位权限',
							icon: 'none'
						});
						resolve(null);
					}
				});
			});
		},
		
		// 打开活动地址的地图导航
		openLocation() {
			if (!this.activityInfo) {
				uni.showToast({
					title: '活动信息不存在',
					icon: 'none'
				});
				return;
			}
			
			const { lng, lat } = this.activityInfo;
			if (!lng || !lat || lng <= 0 || lat <= 0) {
				uni.showToast({
					title: '无法打开位置，缺少地理坐标',
					icon: 'none'
				});
				return;
			}
			
			uni.openLocation({
				latitude: Number(lat),
				longitude: Number(lng),
				name: this.activityInfo?.storeName || '活动地点',
				address: this.activityInfo?.address || ''
			});
		},
		showAgreementModal() {
			uni.showModal({
				title: '报名须知',
				content: '用户首次点击报名时，需弹出并勾选同意以下协议：\n\n1.健康与安全： 请您确保参与活动的宠物身体健康、疫苗接种齐全、无传染性疾病。活动期间请务必系好牵引绳，并自行看管好您的宠物，避免发生走失、打架、误食等意外。如因您看管不力造成任何人身伤害或财产损失，需由您承担相应责任。\n\n2.免责声明： 主办方（一尺花园、SEEWOW）仅为活动提供场地和组织服务，不承担因宠物本身特性、第三方原因或不可抗力导致的任何意外伤害责任。\n\n3.行为规范： 请文明参与活动，爱护场地设施。若您的宠物有严重吠叫、攻击性等行为，主办方有权劝离现场。\n\n4.肖像权使用： 活动期间主办方可能拍摄照片和视频，用于后续宣传推广，报名即视为您同意肖像权的使用。\n\n5.预约与取消： 若因故无法参加，请至少提前24小时在小程序内取消预约，以将名额释放给其他用户。',
				showCancel: true,
				cancelText: '取消',
				cancelColor: '#000000',
				confirmText: '确认授权',
				confirmColor: '#3CC51F',
				success: (res) => {
					if (res.confirm) {
						uni.setStorageSync('agreedToGardenTerms', true);
						this.$refs.registrationDrawer.open();
					} else if (res.cancel) {
						// 用户点击了取消按钮
					}
				}
			});
		},
		
		// 关闭报名抽屉
		closeDrawer() {
			this.$refs.registrationDrawer.close();
			// 重置报名成功状态
			this.registrationSuccess = false;
		},
		
		// 关闭签到弹窗
		closeCheckinModal() {
			this.$refs.checkinModal.close();
			
			// 如果是签到成功，需要刷新页面数据
			if (this.checkinStatus === 'success') {
				// 刷新活动数据以更新用户状态和按钮状态
				this.getDetail();
			}
			
			// 重置签到状态
			this.checkinStatus = null;
			// 重置预约状态
			this.reservationStatus = null;
		},
		
		// 确认报名
		async confirmRegistration() {
			try {
				uni.showLoading({
					title: '报名中...'
				});
				
				const response = await this.$request.post('/api/activity/behavior', {
					activity_id: this.activityInfo?.id,
					type: 2 
				});
				
				uni.hideLoading();
				
				if (response.code === 200) {
					// 报名成功，显示成功界面
					this.registrationSuccess = true;
					// 报名成功后重新获取活动数据，更新用户状态
					const activityId = this.activityInfo?.id;
					this.getDetail();
				} else {
					uni.showToast({
						title: response.message || '报名失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				uni.showToast({
					title: '报名失败，请重试',
					icon: 'none'
				});
			}
		},
		
		// 格式化活动日期
		formatActivityDate(time) {
			if (!time) return 'xx月xx日';
			
			try {
				// 处理可能的日期格式问题
				let dateStr = time;
				
				// 如果是 "4月23日 周日 10:00～22:00" 这种格式，提取日期部分
				const datePattern = /(\d+月\d+日)/;
				const match = time.match(datePattern);
				if (match) {
					return match[1]; // 直接返回 "4月23日" 格式
				}
				
				// 如果是标准日期格式，进行转换
				if (typeof dateStr === 'string' && dateStr.includes('-')) {
					dateStr = dateStr.replace(/-/g, '/'); // iOS兼容性处理
				}
				
				const date = new Date(dateStr);
				
				// 检查日期是否有效
				if (isNaN(date.getTime())) {
					return 'xx月xx日';
				}
				
				const month = date.getMonth() + 1;
				const day = date.getDate();
				return `${month}月${day}日`;
			} catch (error) {
				return 'xx月xx日';
			}
		},
		
		// 分享给好友
		shareToFriend() {
			// 分享功能已通过button的open-type="share"实现
		},
		
		// 返回
		returnToPage() {
			this.closeDrawer();
			// 返回时重新获取活动数据，刷新用户状态
			const activityId = this.activityInfo?.id;
			if (activityId) {
				this.getDetail();
			}
		}
	},
	
	// 微信分享配置
	onShareAppMessage() {
		// 获取当前活动ID，确保分享链接包含activity_id参数
		const activityId = this.activityInfo?.id;
		const path = activityId ? `/pages/garden/index?activity_id=${activityId}` : `/pages/garden/index`;
		
		const rs = {
			title: this.activityInfo?.title || '一起花园活动',
			path: path,
			imageUrl: this.activityInfo?.imgs ? this.activityInfo.imgs.split(',')[0] : ''
		}
		return getIndexShareObject(rs)
	}
}
</script>

<style lang="scss" scoped>
.garden-page {
	min-height: 100vh;
	background: #F7F7F7;
	text-align: center;
	padding: 108rpx 0rpx 342rpx 0rpx;
	position: relative;
	
	.header {
		.gd-icon {
			margin-top: -13rpx;
			width: 64rpx;
			height: 64rpx;
			position: absolute;
			left: 12rpx;
		}
		
		.title {
			font-size: 34rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	// 轮播图样式
	.banner-container {
		overflow: hidden;
		margin-top: 26rpx;
		.banner-swiper {
			height: 500rpx;
			width: 100%;
			
			.banner-image {
				width: 100%;
				height: 100%;
			}
		}
	}

    // 活动简介卡片
    .activity-card {
        width: 718rpx;
        min-height: 382rpx;
        background: #FFFFFF;
        border-radius: 24rpx 24rpx 24rpx 24rpx;
        position: relative;
        z-index: 10;
		padding: 48rpx 48rpx 74rpx 48rpx;
        box-sizing: border-box;
        cursor: pointer;
        transition: all 0.2s ease;
		margin-top: -55rpx;
		margin-left: 16rpx;
        
        &:active {
            transform: scale(0.98);
            opacity: 0.9;
        }
        
        .activity-tag {
            position: absolute;
            top: 0;
            left: 0;
            width: 124rpx;
            height: 42rpx;
            border-radius: 24rpx 0rpx 8rpx 0rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            
            // 报名中状态（默认绿色渐变）
            &.status-active {
                background: linear-gradient( 77deg, #37E465 0%, #2EDBCB 50%, #1FCBDC 100%);
            }
            
            // 已结束状态（灰色）
            &.status-ended {
                background: #CCCCCC;
            }
            
            // 可预约状态（橙色渐变）
            &.status-bookable {
                background: linear-gradient( 90deg, #FEDE44 0%, #FFA437 100%);
            }
            
            .tag-text {
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                font-size: 20rpx;
                color: #FFFFFF;
                text-align: center;
                font-style: normal;
                text-transform: none;
            }
        }
        
        .activity-title {
            display: block;
            font-size: 36rpx;
            font-weight: bold;
            color: #333333;
            margin-top: 20rpx;
            margin-bottom: 24rpx;
            line-height: 1.4;
            text-align: left;
        }
        
        .activity-store {
            display: flex;
            align-items: center;
            font-size: 28rpx;
            color: #7B7B7B;
            margin-bottom: 16rpx;
            
            .store-icon {
                width: 32rpx;
                height: 32rpx;
                margin-right: 12rpx;
            }
        }
        
        .activity-time {
            display: flex;
            align-items: center;
            font-size: 28rpx;
            color: #7B7B7B;
            margin-bottom: 16rpx;
            
            .time-icon {
                width: 32rpx;
                height: 32rpx;
                margin-right: 12rpx;
            }
        }
        
        .activity-location {
            display: flex;
            align-items: center;
            font-size: 28rpx;
            color: #7B7B7B;
            margin-bottom: 32rpx;
            position: relative;

            
            .location-icon {
                width: 32rpx;
                height: 32rpx;
                margin-right: 12rpx;
            }
            
            .navigatio-icon {
                width: 32rpx;
                height: 32rpx;
                position: absolute;
                right: 24rpx;
                top: 50%;
                transfo10: translateY(-50%);
            }
        }
        
        .activity-top-three {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .top-three-avatars {
                display: flex;
                align-items: center;
                
                .top-three-avatar {
                    width: 48rpx;
                    height: 48rpx;
                    border-radius: 50%;
                    margin-right: -12rpx;
                    border: 4rpx solid #FFFFFF;
                    
                    &:last-of-type {
                        margin-right: 16rpx;
                    }
                }
                
                .top-three-text {
                    font-size: 24rpx;
                    color: #999999;
                }
            }
            
            .top-three-remaining {
                font-size: 24rpx;
                color: #FF6B6B;
                font-weight: bold;
            }
        }
        
        // 加载和空状态样式
        &.activity-loading,
        &.activity-empty {
            display: flex;
            align-items: center;
            justify-content: center;
            
            .loading-text,
            .empty-text {
                font-size: 28rpx;
                color: #999999;
            }
        }
        
        // 状态颜色样式
        .top-three-remaining {
            // 可预约状态：橙色
            &.status-bookable {
                color: #FD5219;
            }
            
            // 报名中状态：绿色
            &.status-active {
                color: #00CAC0;
            }
        }
    }
    
    // 活动详情
    .activity-detail {
        padding: 40rpx 16rpx 16rpx 16rpx;
        margin: 24rpx 16rpx 16rpx 24rpx;
        width: 718rpx;
        height: 1008rpx;
        background: #FFFFFF;
        border-radius: 24rpx 24rpx 24rpx 24rpx;
        display: flex;
        flex-direction: column;
        
        .title {
            width: 128rpx;
            height: 40rpx;
            font-weight: 500;
            font-size: 32rpx;
            color: #262626;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }
        
        .activity-detail-image {
            width: 688rpx;
			display: block;
			margin: 0 auto;
			margin-top: 16rpx;
        }
    }
    
    // 购买须知
    .activity-notice {
        padding: 40rpx 32rpx 40rpx 32rpx;
        margin: 24rpx 16rpx 16rpx 16rpx;
        width: 718rpx;
        min-height: 200rpx;
        background: #FFFFFF;
        border-radius: 24rpx 24rpx 24rpx 24rpx;
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
        
        .title {
            display: block;
            font-weight: 500;
            font-size: 32rpx;
            color: #262626;
            text-align: left;
            font-style: normal;
            text-transform: none;
            margin-bottom: 24rpx;
        }
        
        .detail-text {
            display: block;
            font-size: 28rpx;
            color: #666666;
            line-height: 1.6;
            text-align: left;
            word-wrap: break-word;
            white-space: pre-wrap;
        }
    }
	
	// 加载状态样式
	.banner-loading,
	.banner-empty {
		height: 500rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.loading-text,
		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}
	
	.content {
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		
		.description {
			font-size: 30rpx;
			color: #666;
			line-height: 1.6;
		}
	}
	
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 750rpx;
		height: 220rpx;
		background: #FFFFFF;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		z-index: 999;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		padding: 16rpx 40rpx 0 40rpx;
		
		.bottom-bar-store,
		.bottom-bar-note {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			
			.store-icon,
			.note-icon {
				width: 48rpx;
				height: 48rpx;
				margin-bottom: 8rpx;
			}
			
			.store-name,
			.note-name {
				width: 80rpx;
				height: 30rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #262626;
				text-align: center;
				font-style: normal;
				text-transform: none;
				line-height: 30rpx;
				white-space: nowrap;
			}
		}
		
		.bottom-bar-button {
			width: 454rpx;
			height: 96rpx;
			background: #FFDA61;
			border-radius: 70rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.button-text {
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #262626;
			}
		}
	}
	
	// 报名抽屉样式
	.registration-drawer {
		width: 750rpx;
		height: 996rpx;
		background: #FFFFFF;
		border-radius: 24rpx 24rpx 0rpx 0rpx;
		position: relative;
		padding: 8rpx;
		display: flex;
		flex-direction: column;
		
		.close-btn {
			width: 32rpx;
			height: 32rpx;
			border-radius: 0rpx;
			border: 3rpx dashed #999999;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 24rpx;
			margin-left: 694rpx;
			margin-bottom: 8rpx;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		.title {
			width: 128rpx;
			height: 40rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #262626;
			text-align: left;
			font-style: normal;
			text-transform: none;
			margin-left: 24rpx;
			display: block;
		}
		
		.user-info {
			margin-top: 24rpx;
			margin-left: 24rpx;
			display: flex;
			align-items: center;
			margin-bottom: 40rpx;
			
			.user-avatar {
				width: 56rpx;
				height: 56rpx;
				border-radius: 0rpx;
				border: 1rpx solid rgba(204,204,204,0.2);
				margin-right: 20rpx;
			}
			
			.user-name {
				width: 218rpx;
				height: 36rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #262626;
				text-align: left;
				font-style: normal;
				text-transform: none;
			}
		}
		
		.activity-card {
			margin-top: 74rpx;
			position: relative;
			width: 704rpx;
			height: 302rpx;
			margin-bottom: 40rpx;
			border-radius: 12rpx;
			overflow: hidden;
			display: flex;
			flex-direction: column;
			box-sizing: border-box;
			
			.activity-card-bg {
				position: absolute;
				top: 0;
				left: 0;
				width: 704rpx;
				height: 302rpx;
				z-index: 1;
				object-fit: cover;
				object-position: center;
			}
			
			.activity-card-header {
				display: flex;
				justify-content: space-between;
				margin-bottom: 10rpx;
				z-index: 2;
				position: relative;
				
				.activity-card-title {
					width: 466rpx;
					height: 80rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 32rpx;
					color: #262626;
					text-align: left;
					font-style: normal;
					text-transform: none;
				}
				
				.activity-card-icon {
					width: 36rpx;
					height: 36rpx;
				}
			}
			
			.activity-card-end {
				margin-top: 16rpx;
				width: 500rpx;
				height: 30rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #7B7B7B;
				text-align: left;
				font-style: normal;
				text-transform: none;
				z-index: 2;
				position: relative;
			}
			
			.activity-card-remain {
				margin-top: 20rpx;
				width: 300rpx;
				height: 30rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #FD5219;
				text-align: left;
				font-style: normal;
				text-transform: none;
				z-index: 2;
				position: relative;
			}
		}
		
		button {
			width: 670rpx;
			height: 96rpx;
			background: #FFDA61;
			border-radius: 70rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #262626;
			text-align: center;
			font-style: normal;
			text-transform: none;
			border: none;
			display: flex;
			align-items: center;
			justify-content: center;
			position: absolute;
			bottom: 108rpx;
			left: 50%;
			transform: translateX(-50%);
		}
		
		// 报名成功界面样式
		.success-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 48rpx 80rpx 48rpx;
			min-height: 600rpx;
			
			.success-icon {
				width: 142rpx;
				height: 102rpx;
				margin-bottom: 40rpx;
			}
			
			.success-title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 36rpx;
				color: #262626;
				text-align: center;
				margin-bottom: 24rpx;
			}
			
			.success-desc {
				margin-top: 64rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				text-align: center;
				line-height: 40rpx;
				margin-bottom: 80rpx;
			}
			
			.share-btn, .return-btn {
				width: 654rpx;
				height: 96rpx;
				border-radius: 70rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				text-align: center;
				border: none;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			
			.share-btn {
				background: #FFDA61;
				color: #262626;
				margin-bottom: 120rpx;
			}
			
			.return-btn {
				background: #FFFFFF;
				color: #000000;
				border: 3rpx solid #000000;
				margin-bottom: 0;
			}
		}
	}
}

// 签到弹窗样式
.checkin-modal {
	width: 606rpx;
	height: 312rpx;
	background: #FFFFFF;
	border-radius: 24rpx;
	position: relative;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	
	.checkin-close-btn {
		position: absolute;
		top: 24rpx;
		right: 24rpx;
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
		image {
			width: 32rpx;
			height: 32rpx;
		}
	}
	
	.checkin-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.checkin-title {
			margin-top: 56rpx;
			width: 494rpx;
			height: 40rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #262626;
			text-align: center;
			font-style: normal;
			text-transform: none;
		}
		
		.checkin-icon {
			margin-top: 40rpx;
			width: 142rpx;
			height: 102rpx;
			margin-bottom: 24rpx;
		}
		
		.checkin-desc {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #666666;
			text-align: center;
			line-height: 40rpx;
			margin-top: 16rpx;
			margin-bottom: 40rpx;
		}
	}
	
	.checkin-confirm-btn {
		width: 526rpx;
		height: 76rpx;
		background: #FFDA61;
		border-radius: 40rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #262626;
		text-align: center;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 32rpx;
	}
}


</style>